import storage from 'good-storage'

const SEARCH_KEY = '__search__'
const SEARCH_MAX_LENGTH = 15

const PLAY_KEY = '__play__'
const PLAY_MAX_LENGTH = 200

const FAVORITE_KEY = '__favorite__'
const FAVORITE_MAX_LEN = 200
//插入搜索的记录
//arr==数组,val===要插入的数据,compare===数组中是否存在要存入的记录,maxLen====数组最大长度
function insertArray(arr,val,compare,maxLen) {
  //数组中是否有要存入的数据
  const index =  arr.findIndex(compare)
  //第一条数据就不需要做任何事
  if(index === 0){
    return
  }
  //删除
  if(index>0){
    arr.splice(index,1)
  }
  //插入
  arr.unshift(val)
  //删除
  if(maxLen && arr.length>maxLen){
    arr.pop()
  }
}

//存储历史记录
export function saveSearch(query) {
  //当前存储的情况=======如果是没存入就是空数组
  //storage.get（key,def）========得到key,如果没有这个值就默认返回第二个值def
  let searches = storage.get(SEARCH_KEY,[])
  insertArray(searches,query,(item)=>{
    return query === item
  },SEARCH_MAX_LENGTH)
  //storage.set(key,val) ========set一个key，将val存入到key里面去
  storage.set(SEARCH_KEY,searches)
  return searches
}

//本地缓存的数据
export function localStorage() {
  return storage.get(SEARCH_KEY,[])
}


function deleteformArr(arr,compare) {
  const index = arr.findIndex(compare)
  if(index>-1){
    arr.splice(index,1)
  }
}
//删除一条记录
export function deleteSearch(query) {
  let searches = storage.get(SEARCH_KEY,[])
  deleteformArr(searches,(item)=>{
    return item === query
  })
  storage.set(SEARCH_KEY,searches)
  return searches
}

//删除全部记录
export function clearSearch() {
  storage.remove(SEARCH_KEY)
  return []
}

//最近播放 ======= 写(存)
export function savePlay(song) {
  let songs = storage.get(PLAY_KEY, [])
  insertArray(songs, song, (item) => {
    return song.id === item.id
  }, PLAY_MAX_LENGTH)
  storage.set(PLAY_KEY, songs)
  return songs
}
//最近播放==========读
export function loadPlay() {
  return storage.get(PLAY_KEY, [])
}

//收藏=====存
export function saveFavorite(song) {
  let songs = storage.get(FAVORITE_KEY, [])
  insertArray(songs, song, (item) => {
    return song.id === item.id
  }, FAVORITE_MAX_LEN)
  storage.set(FAVORITE_KEY, songs)
  return songs
}
//收藏===删
export function deleteFavorite(song) {
  let songs = storage.get(FAVORITE_KEY, [])
  deleteformArr(songs, (item) => {
    return item.id === song.id
  })
  storage.set(FAVORITE_KEY, songs)
  return songs
}
//收藏====本地缓存
export function loadFavorite() {
  return storage.get(FAVORITE_KEY, [])
}
